package com.yj.blog.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.yj.blog.admin.bo.SysUserDetails;
import com.yj.blog.admin.dao.SysUserRoleRelationDao;
import com.yj.blog.admin.dto.SysUserParam;
import com.yj.blog.admin.dto.UpdateUserPasswordParam;
import com.yj.blog.admin.service.SysUserService;
import com.yj.blog.common.exception.Asserts;
import com.yj.blog.common.util.RequestUtil;
import com.yj.blog.model.*;
import com.yj.blog.admin.service.SysUserCacheService;
import com.yj.blog.mapper.SysUserLoginLogMapper;
import com.yj.blog.mapper.SysUserMapper;
import com.yj.blog.mapper.SysUserRoleRelationMapper;
import com.yj.blog.security.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户管理Service实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleRelationMapper userRoleRelationMapper;
    @Autowired
    private SysUserRoleRelationDao userRoleRelationDao;
    @Autowired
    private SysUserLoginLogMapper loginLogMapper;
    @Autowired
    private SysUserCacheService userCacheService;

    @Override
    public SysUser getUserByUsername(String username) {
        SysUser user = userCacheService.getUser(username);
        if(user!=null) return  user;
        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<SysUser> userList = userMapper.selectByExample(example);
        if (userList != null && userList.size() > 0) {
            user = userList.get(0);
            userCacheService.setUser(user);
            return user;
        }
        return null;
    }

    @Override
    public SysUser register(SysUserParam sysUserParam) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserParam, sysUser);
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(1);
        //查询是否有相同用户名的用户
        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameEqualTo(sysUser.getUsername());
        List<SysUser> sysUserList = userMapper.selectByExample(example);
        if (sysUserList.size() > 0) {
            return null;
        }
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(encodePassword);
        userMapper.insert(sysUser);
        return sysUser;
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                Asserts.fail("密码不正确");
            }
            if(!userDetails.isEnabled()){
                Asserts.fail("帐号已被禁用");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            updateLoginTimeByUsername(username);
            insertLoginLog(username);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    /**
     * 添加登录记录
     * @param username 用户名
     */
    private void insertLoginLog(String username) {
        SysUser user = getUserByUsername(username);
        if(user==null) return;
        SysUserLoginLog loginLog = new SysUserLoginLog();
        loginLog.setUserId(user.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        loginLog.setIp(RequestUtil.getRequestIp(request));
        loginLogMapper.insert(loginLog);
    }

    /**
     * 根据用户名修改登录时间
     */
    private void updateLoginTimeByUsername(String username) {
        SysUser record = new SysUser();
        record.setLoginTime(new Date());
        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        userMapper.updateByExampleSelective(record, example);
    }

    @Override
    public String refreshToken(String oldToken) {
        return jwtTokenUtil.refreshHeadToken(oldToken);
    }

    @Override
    public SysUser getItem(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SysUser> list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andUsernameLike("%" + keyword + "%");
            example.or(example.createCriteria().andNickNameLike("%" + keyword + "%"));
        }
        return userMapper.selectByExample(example);
    }

    @Override
    public int update(Long id, SysUser user) {
        user.setId(id);
        SysUser rawUser = userMapper.selectByPrimaryKey(id);
        if(rawUser.getPassword().equals(user.getPassword())){
            //与原加密密码相同的不需要修改
            user.setPassword(null);
        }else{
            //与原加密密码不同的需要加密修改
            if(StrUtil.isEmpty(user.getPassword())){
                user.setPassword(null);
            }else{
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }
        }
        int count = userMapper.updateByPrimaryKeySelective(user);
        userCacheService.delUser(id);
        return count;
    }

    @Override
    public int delete(Long id) {
        userCacheService.delUser(id);
        int count = userMapper.deleteByPrimaryKey(id);
        userCacheService.delResourceList(id);
        return count;
    }

    @Override
    public int updateRole(Long userId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        //先删除原来的关系
        SysUserRoleRelationExample userRoleRelationExample = new SysUserRoleRelationExample();
        userRoleRelationExample.createCriteria().andUserIdEqualTo(userId);
        userRoleRelationMapper.deleteByExample(userRoleRelationExample);
        //建立新关系
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<SysUserRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                SysUserRoleRelation roleRelation = new SysUserRoleRelation();
                roleRelation.setUserId(userId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            userRoleRelationDao.insertList(list);
        }
        userCacheService.delResourceList(userId);
        return count;
    }

    @Override
    public List<SysRole> getRoleList(Long userId) {
        return userRoleRelationDao.getRoleList(userId);
    }

    @Override
    public List<SysResource> getResourceList(Long userId) {
        List<SysResource> resourceList = userCacheService.getResourceList(userId);
        if(CollUtil.isNotEmpty(resourceList)){
            return  resourceList;
        }
        resourceList = userRoleRelationDao.getResourceList(userId);
        if(CollUtil.isNotEmpty(resourceList)){
            userCacheService.setResourceList(userId,resourceList);
        }
        return resourceList;
    }

    @Override
    public int updatePassword(UpdateUserPasswordParam param) {
        if(StrUtil.isEmpty(param.getUsername())
                ||StrUtil.isEmpty(param.getOldPassword())
                ||StrUtil.isEmpty(param.getNewPassword())){
            return -1;
        }
        SysUserExample example = new SysUserExample();
        example.createCriteria().andUsernameEqualTo(param.getUsername());
        List<SysUser> userList = userMapper.selectByExample(example);
        if(CollUtil.isEmpty(userList)){
            return -2;
        }
        SysUser sysUser = userList.get(0);
        if(!passwordEncoder.matches(param.getOldPassword(),sysUser.getPassword())){
            return -3;
        }
        sysUser.setPassword(passwordEncoder.encode(param.getNewPassword()));
        userMapper.updateByPrimaryKey(sysUser);
        userCacheService.delUser(sysUser.getId());
        return 1;
    }

    @Override
    public UserDetails loadUserByUsername(String username){
        //获取用户信息
        SysUser user = getUserByUsername(username);
        if (user != null) {
            List<SysResource> resourceList = getResourceList(user.getId());
            return new SysUserDetails(user,resourceList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
